# -*- coding: utf-8 -*-            
# @Time : 2022/8/9 16:25
# @FileName: utils.py
# @Target:
import logging
import time
import os
import json
import codecs
import requests
from pprint import pprint

class Qwen2(object):
    '''
    Qwen IDMI 算法处理对应的 CuZu 数据
    '''

    def __init__(self):
        self.csp_url = "http://117.50.174.71:8765/csp_analysis"
        self.feel_url = "http://117.50.174.71:8765/feel_analysis"
        self.ner_url = "http://117.50.174.71:8765/ner_analysis"
        self.clarify_quality_url = "http://117.50.174.71:8765/clarify_quality_analysis"
        self.quality_url = "http://117.50.174.71:8765/quality_analysis"
        self.headers = {
            "accept": "application/json",
            "Content-Type": "application/json"
        }

    def clean_sentence(self, customer_voice):
        return customer_voice. \
            replace('\r', ''). \
            replace('\n', ''). \
            replace('\t', ''). \
            replace('"', ''). \
            replace("'", ""). \
            replace('  ', "")

    def csp(self, customer_voice):
        if len(customer_voice):
            customer_voice = self.clean_sentence(customer_voice)
            data = {
                "customer_voice": customer_voice
            }
            res = requests.post(self.csp_url,
                                headers=self.headers,
                                data=json.dumps(data))
            res = json.loads(res.content.decode('unicode_escape'))
            if res['message']['status_code'] == 200:
                result = res['message']['result']
                return result
            else:
                return None
        else:
            return None

    def feel(self, customer_voice):
        if len(customer_voice):
            customer_voice = self.clean_sentence(customer_voice)
            data = {
                "customer_voice": customer_voice
            }
            res = requests.post(self.feel_url, headers=self.headers, data=json.dumps(data))
            res = json.loads(res.content.decode('unicode_escape'))
            if res['message']['status_code'] == 200:
                result = res['message']['result']
                try:
                    _llm_feeling, _llm_feeling_en = result
                    llm_feeling_en = []
                    # TODO : modify this place
                    for llm in _llm_feeling_en :
                        _content_list = llm['content_list']
                        feel_1 = llm['feel_1']
                        feel_2 = llm['feel_2']
                        sentiment = llm['sentiment']
                        content_list = []
                        for content in _content_list :
                            content_en = idmi_nlp_tool._translate_util_zh2en(content)['en']
                            content_list.append(content_en)
                        llm_feeling_en.append({
                            'feel_1' : feel_1, 'feel_2' : feel_2,
                            'content_list' : content_list, 'sentiment' : sentiment
                        })
                    result = [_llm_feeling, llm_feeling_en]
                except :
                    result = result
                return result
            else:
                return None
        else:
            return None

    def ner(self, customer_voice, content):
        if len(customer_voice) and len(content):
            customer_voice = self.clean_sentence(customer_voice)
            data = {
                "content": content,
                "customer_voice": customer_voice
            }
            res = requests.post(self.ner_url,
                                headers=self.headers,
                                data=json.dumps(data))
            res = json.loads(res.content.decode('unicode_escape'))
            if res['message']['status_code'] == 200:
                result = res['message']['result']
                return result
            else:
                return None
        else:
            return None

    def clarify_quality(self, customer_voice) -> bool:
        if len(customer_voice):
            customer_voice = self.clean_sentence(customer_voice)
            data = {
                "content": customer_voice,
                "customer_voice": customer_voice
            }
            res = requests.post(self.clarify_quality_url,
                                headers=self.headers,
                                data=json.dumps(data))
            res = json.loads(res.content.decode('unicode_escape'))
            if res['message']['status_code'] == 200:
                result = res['message']['result']
                if '客户抱怨车辆质量问题' in result:
                    return True
                else:
                    return False
            else:
                return False
        else:
            return False

    def quality(self, customer_voice):
        if len(customer_voice):
            customer_voice = self.clean_sentence(customer_voice)
            data = {
                "customer_voice": customer_voice,
                "type": 'quality'
            }
            res = requests.post(self.quality_url,
                                headers=self.headers,
                                data=json.dumps(data))
            res = json.loads(res.content.decode('unicode_escape'))
            if res['message']['status_code'] == 200:
                result = res['message']['result']
                return result
            else:
                return False
        else:
            return None

    def quality_and_ner(self, customer_voice):
        if len(customer_voice):
            customer_voice = self.clean_sentence(customer_voice)
            data = {
                "customer_voice": customer_voice,
                "type": 'quality_and_ner'
            }
            res = requests.post(self.quality_url,
                                headers=self.headers,
                                data=json.dumps(data))
            res = json.loads(res.content.decode('unicode_escape'))
            if res['message']['status_code'] == 200:
                result = res['message']['result']
                return result
            else:
                return False
        else:
            return None


if __name__ == '__main__':
    qwen = Qwen2()
    customer_voice = "一汽大众宝来变速箱故障灯报警，变速箱锁挡踩油门没动力，要求处理。"
    A = qwen.quality(customer_voice=customer_voice)
    pprint(A)


# TODO : IDMI NLP TOOL
class IDMI_NLP_TOOL:
    def __init__(self):
        self.TRANSLATE_URL = 'http://152.32.135.145:17300/translate'
        # self.quality_multilabel_url = "http://152.32.135.145:17200/multi-label/predict"
        self.qwen = Qwen2()

    def _sentence_strip(self, sentence):
        sentence = sentence. \
            replace('\r', ''). \
            replace('\n', ''). \
            replace('\t', ''). \
            replace('"', ''). \
            replace("'", ""). \
            replace('“', ' '). \
            replace('”', ' '). \
            replace('{', ' '). \
            replace('}', ' ')

        return sentence

        # return ''.join([_.strip() for _ in sentence])

    def quality_multi_label(
            self,
            sourceId : str,
            title: str,
            text: str
    ):
        '''
        20220714 convert the 12365auto quality code into VW quality issues
        20240925 within usage of Qwen to determine the customer voice has quality issues or not
        20241207 all the quality analysis to use Qwen2.5
        '''
        if sourceId.startswith('complaint'):
            # current customer voice from complaint platform
            # title = self._sentence_strip(title)
            # text = self._sentence_strip(text)
            # _res = requests.post(url=self.quality_multilabel_url,
            #                      data=dict(title=title, text=text))
            # _res = json.loads(_res.content.decode("unicode_escape"))
            # pred_names, _ = _res['pred_names'], _res['pred_names_index']
            # # print(pred_names) # ['车身附件及电器@@影音系统故障', '车身附件及电器@@车内异响', '其他@@疑似减配']
            # for pred_name in pred_names:
            #     function_group , problem = pred_name.split('@@')
            #     try:
            #         content_list = self.qwen.ner(customer_voice=str(title) + str(text), content=problem)
            #     except:
            #         content_list = []
            #     res_quality_multi_labels.append(
            #         {
            #             'function_group': function_group,
            #             'problem': problem,
            #             'content_list': content_list,
            #             'sentiment': '负向情感'
            #         }
            #     )
            # return res_quality_multi_labels
            title = self._sentence_strip(title)
            text = self._sentence_strip(text)
            customer_voice = title + text
            zh, en = self.qwen.quality_and_ner(
                customer_voice=customer_voice
            )
            function_group_problem_zh = zh
            function_group_problem_en = en
        else:
            # current customer voice from forum platform
            title = self._sentence_strip(title)
            text = self._sentence_strip(text)
            customer_voice = title + text
            quality_FLAG = self.qwen.clarify_quality(customer_voice=customer_voice)
            if quality_FLAG:
                zh, en = self.qwen.quality_and_ner(
                    customer_voice=customer_voice
                )
                function_group_problem_zh = zh
                function_group_problem_en = en
            else:
                function_group_problem_zh = []
                function_group_problem_en = []
        return function_group_problem_zh, function_group_problem_en


    def _translate_util_zh2en(self, sentence):
        if isinstance(sentence, str):
            data = {
                'sentence': sentence,
                'src_language_type': 'zh',
                'tar_language_type': 'en',
                'password': 'liuyang177'
            }
            res = requests.post(
                url=self.TRANSLATE_URL,
                data=data
            )
            return json.loads(res.content.decode('unicode_escape'))
        else:
            return {
                "en": "",
                "zh": ""
            }

    def translate_util_zh2en(self, title, text):
        try:
            if len(title):
                title_en = self._translate_util_zh2en(title)['en']
            else:
                title_en = ''
            if len(text):
                text_en = self._translate_util_zh2en(text)['en']
            else:
                text_en = ''
            return {'title_en': title_en,
                    'text_en': text_en,
                    'translate_success': True}
        except Exception as e:
            return {'title_en': '',
                    'text_en': '',
                    'translate_success': False}

    def response(self,
                 title,
                 text,
                 if_translate,
                 sourceId):
        title = self._sentence_strip(title)
        text = self._sentence_strip(text)
        if len(title + text):
            # FLAG_sentence_valid = True
            function_group_problem_zh, function_group_problem_en = self.quality_multi_label(sourceId, title, text)
            Ncvqs_labels = []
            # Ncvqs_labels = self.zh_post_ncvqs_label(title, text)
            FLAG_function_group_problem = True if len(function_group_problem_zh) else False
            # FLAG_ncvqs = True if len(Ncvqs_labels) else False
            FLAG_ncvqs = False

            if if_translate:
                if FLAG_function_group_problem:
                    Translate_labels = self.translate_util_zh2en(title, text)

                    # if_translate needed , translate the function_group_problem_en
                    try:
                        _function_group_problem_en = []
                        for fp in function_group_problem_en:
                            # [{"content_list": ["车内柴油味特别大"], "function_group": "Body accessories and electrical appliances",
                            #   "problem": "Interior odor", "sentiment": "negative"}]
                            content_list = fp['content_list']
                            function_group = fp['function_group']
                            problem = fp['problem']
                            sentiment = fp['sentiment']
                            _content_list = []
                            for content in content_list:
                                content_en = self._translate_util_zh2en(content)['en']
                                _content_list.append(content_en)
                            _function_group_problem_en.append({
                                'function_group': function_group,
                                'problem': problem,
                                'content_list': _content_list,
                                'sentiment': sentiment
                            })
                        function_group_problem_en = _function_group_problem_en
                    except :
                        function_group_problem_en = function_group_problem_en


                else:
                    Translate_labels = {'title_en': '', 'text_en': '', 'translate_success': False}
            else:
                Translate_labels = {'title_en': '', 'text_en': '', 'translate_success': False}

            return {
                'FLAG_function_group_problem': FLAG_function_group_problem,
                'function_group_problem_zh': function_group_problem_zh,
                'function_group_problem_en': function_group_problem_en,
                'title': title,
                'text': text,
                'title_en': Translate_labels['title_en'],
                'text_en': Translate_labels['text_en'],
                'translate_success': Translate_labels['translate_success']
            }
        else:
            return {
                'FLAG_function_group_problem': False,
                'function_group_problem_zh': [],
                'function_group_problem_en': [],
                'title': '',
                'text': '',
                'title_en': '',
                'text_en': '',
                'translate_success': False
            }


idmi_nlp_tool = IDMI_NLP_TOOL()

if __name__ == '__main__':
    ...
    title = "一汽红旗H5车内异响 车机卡顿 carlife减配"
    text = "麻烦厂家不要把所有的问题都交给4s店来处理，车机互联，carlife、carplay、hicar这些是厂家工作人员的不作为，我想说的是有些问题要让厂家来支持改进，4s店只是给我们解决力所能及的事情，4s店的服务态度可以，厂家就不能做得好一点？希望厂家好好处理所存在的问题，如此垃圾的车机、地图不跟新、不支持互联，在互联时代，希望厂家好好解决吧！"
    A = idmi_nlp_tool.response(title, text, True, 'complaint_')
    print(A)
else:
    ...


# 接下来处理对应的 model name 的对应关系
class Mapping_Brand_Series(object):
    def __init__(self):
        with codecs.open(
                filename='idmi_backend/model_config_DICT.json',
                mode='r', encoding='utf-8') as fr:
            self.DICT = json.load(fr)

    def mapping_get(self,
                    sourceId,
                    ___brand_src,
                    ___series_src):
        brand, series = '', ''
        if sourceId in [
            'complaint_12365auto', 'complaint_315auto', 'complaint_315qc', 'complaint_aqsiqauto',
            'complaint_autohome', 'complaint_qctsw', 'complaint_qiche365', 'complaint_qichemen'
        ]:
            complaint_12365auto_DICT = self.DICT[sourceId]
            if ___brand_src in complaint_12365auto_DICT.keys():
                series_keys = complaint_12365auto_DICT[___brand_src].keys()
                for series_key in series_keys:
                    if series_key in ___series_src:
                       brand, series = complaint_12365auto_DICT[___brand_src][series_key]
            return brand, series
        else:
            return brand, series

mapping_brand_series = Mapping_Brand_Series()






